package cn.hnh.service.impl;

import cn.hnh.constrant.RedisKeys;
import cn.hnh.constrant.ResultInfo;
import cn.hnh.mapper.ArticleMapper;
import cn.hnh.service.IndexService;
import cn.hnh.utils.DateFormatUtils;
import cn.hnh.utils.RedisUtils;
import cn.hnh.vo.ArticleTitleVo;
import cn.hnh.vo.IndexVo;
import cn.hnh.vo.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author HuangNianHong
 * @Time 2021/1/5
 */
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Result<IndexVo> getIndexVo(Integer pagenum) {
        PageHelper.startPage(pagenum,5);
        List<ArticleTitleVo> list = articleMapper.getArticleTitle();
        PageInfo<ArticleTitleVo> pageinfo = new PageInfo<>(list);
        if(pageinfo.getPages()!=0){
            IndexVo vo = new IndexVo();
            vo.setHasNextPage(pageinfo.isHasNextPage());
            vo.setTotalpage(pageinfo.getPages());
            vo.setHasPreviousPage(pageinfo.isHasPreviousPage());
            vo.setPageNum(pageinfo.getPageNum());
            vo.setNextPageNum(pageinfo.getNextPage());
            vo.setPrePageNum(pageinfo.getPrePage());
            List<ArticleTitleVo> articleTitleVoList = pageinfo.getList();
            for (ArticleTitleVo articleTitleVo : articleTitleVoList) {
                articleTitleVo.setDate(DateFormatUtils.formatDate(articleTitleVo.getTime()));
                Object count = redisUtils.get(RedisKeys.ARTICLE_VIEW_COUNT + articleTitleVo.getId());
                Integer readCount=count==null?0: (Integer) count;
                articleTitleVo.setReadCount(readCount);
            }
            vo.setInfo(articleTitleVoList);
            return new Result<>(ResultInfo.SUCCESS_CODE,ResultInfo.SUCCESS_MESSAGE,vo);
        }
        return new Result<>(ResultInfo.NOTFOUND_CODE,ResultInfo.NOTFOUND_MESSAGE);
    }
}
